import { login, getUserInfo, setSelfInfo } from "@/amtf/api/user"
import { jsonInBlacklist } from "@/amtf/api/jwt"
import router from "@/router/index"
import { ElLoading, ElMessage } from "element-plus"
import { defineStore } from "pinia"
import { ref, computed, watch, reactive } from "vue"
import { useRouterStore } from "@/stores/use_router_store"
import cookie from "js-cookie"
import { useRouter } from "vue-router"
import * as util from "@/utils"

import { useAppStore } from "@/stores"

export const useUserStore = defineStore("user", () => {
    const appStore = useAppStore()
    const loadingInstance = ref(null)

    const userInfo = reactive({
        uuid: "",
        nick_name: "",
        avatar: "",
        authority: {},
    })

    const token = ref(window.localStorage.getItem("token") || cookie.get("x-token") || "")

    const setUserInfo = val => {
        // userInfo = val
        util.对象重予(userInfo, val)
        // console.log(`userInfo 👉`,userInfo)
        if (val.origin_setting) {
            Object.keys(appStore.config).forEach(key => {
                appStore.config[key] = val.origin_setting[key]
            })
        }
    }

    const setToken = val => {
        token.value = val
    }

    const NeedInit = async () => {
        token.value = ""
        window.localStorage.removeItem("token")
        await router.push({ name: "Init", replace: true })
    }

    const ResetUserInfo = (value = {}) => {
        util.对象重予(userInfo, {
            ...userInfo,
            ...value,
        })
        // userInfo = {
        //     ...userInfo,
        //     ...value,
        // }
    }

    const GetUserInfo = async () => {
        const res = await getUserInfo()
        if (res.code === 0) {
            // console.log(`res.data.userInfo 👉`,res.data.userInfo)
            setUserInfo(res.data.userInfo)
        }
        return res
    }

    const LoginIn = async loginInfo => {
        loadingInstance.value = ElLoading.service({
            fullscreen: true,
            text: "登录中，请稍候...",
        })
        const res = await login(loginInfo)
        // 登陆失败，直接返回
        if (res.code !== 0) {
            loadingInstance.value.close()
            return false
        }
        // 登陆成功，设置用户信息和权限相关信息
        setUserInfo(res.data.user)
        setToken(res.data.token)

        // 初始化路由信息
        const routerStore = useRouterStore()
        await routerStore.SetAsyncRouter()
        const asyncRouters = routerStore.asyncRouters

        // 注册到路由表里
        asyncRouters.forEach(asyncRouter => {
            router.addRoute(asyncRouter)
        })

        if (!router.hasRoute(userInfo.authority.defaultRouter)) {
            ElMessage.error("请联系管理员进行授权")
        } else {
            await router.replace({ name: userInfo.authority.defaultRouter })
        }

        const isWin = ref(/windows/i.test(navigator.userAgent))
        if (isWin.value) {
            window.localStorage.setItem("osType", "WIN")
        } else {
            window.localStorage.setItem("osType", "MAC")
        }

        // 全部操作均结束，关闭loading并返回
        loadingInstance.value.close()
        return true
    }

    const 是开发者否 = computed(() => {
        const res = util.含其中之一(userInfo.authority.authorityName, ["管理员", "开发者"])
        // userInfo.authority.authorityName
        return res
    })

    const Router = useRouter()
    const 主页路由name = computed(() => {
        let res = userInfo.authority.defaultRouter
        if (!res) {
            // router 的name
            res = "home"
        }
        return res
    })

    const 主页路由 = computed(() => {
        let 全部路由 = Router.getRoutes()
        // console.log(`全部路由 👉`, 全部路由)
        let layout = util.查元素(全部路由, "layout", "name")
        // console.log(`layout 👉`, layout)
        let res = util.查元素(layout.children, 主页路由name.value, "name")
        // console.log(`返回主页res 👉`, res)
        return res
    })

    /* 登出*/
    const LoginOut = async () => {
        const res = await jsonInBlacklist()
        // 登出失败
        if (res.code !== 0) {
            return
        }
        await ClearStorage()
        // 把路由定向到登录页，无需等待直接reload
        router.push({ name: "Login", replace: true })
        window.location.reload()
    }
    /* 清理数据 */
    const ClearStorage = async () => {
        token.value = ""
        sessionStorage.clear()
        window.localStorage.removeItem("token")
        cookie.remove("x-token")
        localStorage.removeItem("origin_setting")
    }

    watch(
        () => token.value,
        () => {
            window.localStorage.setItem("token", token.value)
        }
    )

    return {
        是开发者否,
        主页路由name,
        主页路由,
        userInfo,
        token,
        NeedInit,
        ResetUserInfo,
        GetUserInfo,
        LoginIn,
        LoginOut,
        setToken,
        loadingInstance,
        ClearStorage,
    }
})
